package com.dong.security;

import cn.hutool.core.util.StrUtil;
import com.dong.entity.SysUser;
import com.dong.service.ISysUserService;
import com.dong.utils.JwtUtils;
import com.jhlabs.math.VLNoise;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName JWTAuthenticationFilter.java
 * @Description TODO
 * @createTime 2022年05月27日 14:32:00
 */
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    ISysUserService sysUserService;


    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtils.getHeader());
        if (StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request,response);
            return;
        }
        Claims claim = jwtUtils.getClaimByToken(jwt);
        if (claim == null){
            throw new JwtException("token异常");
        }
        if (jwtUtils.isTokenExpired(claim)){
            throw new JwtException("token已过期");
        }

        String username = claim.getSubject();
        //获取用户的权限等信息

        SysUser sysUser = sysUserService.getByUserName(username);

        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(username, null ,userDetailService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);
    }


}
